<?php

App::uses('AppController', 'Controller');

/**
 * Posts Controller
 *
 * @property Post $Post
 * @property PaginatorComponent $Paginator
 */
class PostsController extends AppController {

    /**
     * Components
     *
     * @var array
     */
    public $components = array('Paginator', 'Session', 'RequestHandler');
    public $helpers = array('Form', 'Html', 'Counter', 
        'Js', 'Time', 'Session');
    /**
     * index method
     *
     * @return void
     */
    /*
     * index method
     *
     * @return void
     */
    public function beforeFilter() {


        $this->Auth->allow('display', 'index', 'face', 'view','send', 'deletefavorite','favorite','contact','adsadd', 'resent','editads', 'delete', 'manageads', 'add', 'register', 'login', 'facelogout', 'allads', 'msregister', 'article', 'search', 'forgotpws', 'resetemail', 'activated', 'edituser', 'comments', 'deleteComment');

       
        Controller::loadModel('Menu');
        $this->set('menus', $this->Menu->Find('all', array('conditions' => array('Menu.position' => '0'), 'order' => array('Menu.order' => 'asc'))));
        $this->set('menusbottom', $this->Menu->Find('all', array('conditions' => array('Menu.position' => '1'), 'order' => array('Menu.order' => 'asc'))));
        $this->set('menusleft', $this->Menu->Find('all', array('conditions' => array('Menu.position' => '2'), 'order' => array('Menu.order' => 'asc'))));

        Controller::loadModel('Paid_ads');
        $myDate = date("Y-m-d");
        // Left Ads
        $leftads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 2, 'Paid_ads.expired >=' => $myDate))));
        $this->set('leftbanners', $leftads);

        // Right Ads
        $rightads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 3, 'Paid_ads.expired >=' => $myDate))));
        $this->set('rightbanners', $rightads);

        // Top Header Ads
        $topheaderads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 4, 'Paid_ads.expired >=' => $myDate))));
        $this->set('topheaderads', $topheaderads);

        // Top Header Ads
        $bannerads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 5, 'Paid_ads.expired >=' => $myDate))));
        $this->set('bannerads', $bannerads);

        // Top Content Ads
        $topcontentads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 6, 'Paid_ads.expired >=' => $myDate))));
        $this->set('topcontentads', $topcontentads);

        // Top Content Ads
        $middlecontentads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 7, 'Paid_ads.expired >=' => $myDate))));
        $this->set('middlecontentads', $middlecontentads);

        // Top Content Ads
        $bottomcontentads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 8, 'Paid_ads.expired >=' => $myDate))));
        $this->set('bottomcontentads', $bottomcontentads);
        
        // Left Sidebar Ads
        $leftsidebarads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 9, 'Paid_ads.expired >=' => $myDate))));
        $this->set('leftsidebarads', $leftsidebarads);
        
        // Right Sidebar Ads
        $rightsidebarads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 10, 'Paid_ads.expired >=' => $myDate))));
        $this->set('rightsidebarads', $rightsidebarads);

        Controller::loadModel('Category');
        Controller::loadModel('Location');
        $nodelist = $this->Category->generateTreeList(null, null, null, " - ");

//			$this->set('parents',$this->Category->generatetreelist());
        $this->set('parents', ($nodelist));
        $categories = $this->Category->find('list');
        $locations = $this->Location->find('list');
        $this->set(compact('locations'));
        $this->set('params', '');
        Controller::loadModel('Product');
        if($this->Session->check('order')){
           $data = $this->Session->read('order');
            $favoriteproduct = $this->Product->find('all', array('conditions' => array('Product.id' => $data)));
            $this->set('favoriteproducts', $favoriteproduct);
        }
           $this->layout = 'home';
    }

    public function face() {
        
    }
    public function deletefavorite($index=null){
            $this->layout = 'home';
//          $products = $this->Session->read('order');
//          echo $index;
//          print_r($products);
//          die();
        if ($this->Session->check('order')) {
            $products = $this->Session->read('order');
//            pr($products);
            $newProducts = array();
            if ($products) {
                if (array_key_exists($index, $products)) {
                    unset($products[$index]);
                }
                $newProducts = array_values($products);
                $filters=array_filter($newProducts);
                $this->Session->write('order', $filters);
//                pr($newProducts);
//                die();
                $this->redirect($this->referer());
            }
        }
        
    }
  public function favorite($id=null) {
      $this->layout = 'home';
        Controller::loadModel('Product');
        Controller::loadModel('Statistic');
        Controller::loadModel('Comment');
        Controller::loadModel('User');
        
        $countstatistic = $this->Statistic->find('all', array('conditions' => array('Statistic.date' => $date = date('Y/m/d'))));
        $this->set('counttoday', $countstatistic);
        $data;
        if($this->RequestHandler->isAjax()){
        if ($this->Session->check('order')) {
            $data = $this->Session->read('order');
            array_push($data, $id);
            $this->Session->write('order', $data);
        } else {
            $data=array($id);
            $this->Session->write('order', $data);
        }
        } 
         $data=$this->Session->read('order');
        $favoriteproduct = $this->Product->find('all', array('conditions' => array('Product.id' => $data)));
        $this->set('favoriteproducts', $favoriteproduct);
        
        //$this->Session->delete('order');
        // $a= $this->Session->read('order');
        print_r($data);
    }

    public function editads($id = null) {
         $this->layout = 'home';
        Controller::loadModel('Product');
        if ($this->Auth->user('role') && $this->Auth->user('role') == 'Register') {
            if (!$this->Product->exists($id)) {
                throw new NotFoundException(__('Invalid product'));
            }
            $oldProduct = $this->Product->find('all', array('conditions' => array('Product.id' => $id)));
            if ($this->request->is(array('post', 'put'))) {
                $this->Product->create();
                $validate = true;
                $allowedMime = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/jpg');

                // Control Picture of Before
                $requestimage = $this->request->data['Product']['picture1'];
                $newfilename = date("YmdGis") . $requestimage['name'];
                if (!empty($this->request->data['Product']['picture1']['name'])) {
                    $image1 = $newfilename;
                } else {
                    $image1 = $oldProduct[0]['Product']['picture1'];
                }

                if (!empty($requestimage['type']) && in_array($requestimage['type'], $allowedMime)) {
                    if (!move_uploaded_file($requestimage['tmp_name'], WWW_ROOT . 'img' . DS . 'uploads' . DS . $newfilename)) {
                        $this->Product->invalidate('picture1', 'File was not uploaded, please try again.');
                        $validate = false;
                    } else {
                        $this->request->data['Product']['picture1'] = $newfilename;
                    }
                    //indicate which file to resize (can be any type jpg/png/gif/etc...)
                    $file = 'img/uploads/' . $newfilename;

                    //indicate the path and name for the new resized file
                    $resizedFile = 'img/uploads/images_resize/' . $newfilename;
                    $this->smart_resize_image($file, 100, 100, false, $resizedFile, false, false, 100);
                    $picture1 = new File(WWW_ROOT . "/img/uploads/images_resize/" . $oldProduct[0]['Product']['picture1']);
                    $picture1->delete();
                    $picture1 = new File(WWW_ROOT . "/img/uploads/" . $oldProduct[0]['Product']['picture1']);
                    $picture1->delete();
                } else {
                    if (!empty($requestimage['tmp_name'])) {
                        $this->Product->invalidate('picture1', 'Please supply a valid image (.jpg, .gif or .png)');
                        $validate = false;
                    } else {
                        $this->request->data['Product']['picture1'] = NULL;
                    }
                }
                // Control Picture2 of Before
                $requestimage2 = $this->request->data['Product']['picture2'];
                $newfilename2 = date("YmdGis") . $requestimage2['name'];
                if (!empty($this->request->data['Product']['picture2']['name'])) {
                    $image2 = $newfilename2;
                } else {
                    $image2 = $oldProduct[0]['Product']['picture2'];
                }

                if (!empty($requestimage2['type']) && in_array($requestimage2['type'], $allowedMime)) {
                    if (!move_uploaded_file($requestimage2['tmp_name'], WWW_ROOT . 'img' . DS . 'uploads' . DS . $newfilename2)) {
                        $this->Product->invalidate('picture2', 'File was not uploaded, please try again.');
                        $validate = false;
                    } else {
                        $this->request->data['Product']['picture2'] = $newfilename2;
                    }

                    //indicate which file to resize (can be any type jpg/png/gif/etc...)
                    $file = 'img/uploads/' . $newfilename2;

                    //indicate the path and name for the new resized file
                    $resizedFile = 'img/uploads/images_resize/' . $newfilename2;
                    $this->smart_resize_image($file, 100, 100, false, $resizedFile, false, false, 100);
                    $picture2 = new File(WWW_ROOT . "/img/uploads/images_resize/" . $oldProduct[0]['Product']['picture2']);
                    $picture2->delete();
                    $picture2 = new File(WWW_ROOT . "/img/uploads/" . $oldProduct[0]['Product']['picture2']);
                    $picture2->delete();
                } else {
                    if (!empty($requestimage2['tmp_name'])) {
                        $this->Product->invalidate('picture2', 'Please supply a valid image (.jpg, .gif or .png)');
                        $validate = false;
                    } else {
                        $this->request->data['Product']['picture2'] = NULL;
                    }
                }
                // Control Picture3 of Before
                $requestimage3 = $this->request->data['Product']['picture3'];
                $newfilename3 = date("YmdGis") . $requestimage3['name'];
                if (!empty($this->request->data['Product']['picture3']['name'])) {
                    $image3 = $newfilename3;
                } else {
                    $image3 = $oldProduct[0]['Product']['picture3'];
                }

                if (!empty($requestimage3['type']) && in_array($requestimage3['type'], $allowedMime)) {
                    if (!move_uploaded_file($requestimage3['tmp_name'], WWW_ROOT . 'img' . DS . 'uploads' . DS . $newfilename3)) {
                        $this->Product->invalidate('picture3', 'File was not uploaded, please try again.');
                        $validate = false;
                    } else {
                        $this->request->data['Product']['picture3'] = $newfilename3;
                    }

                    //indicate which file to resize (can be any type jpg/png/gif/etc...)
                    $file = 'img/uploads/' . $newfilename3;

                    //indicate the path and name for the new resized file
                    $resizedFile = 'img/uploads/images_resize/' . $newfilename3;
                    $this->smart_resize_image($file, 100, 100, false, $resizedFile, false, false, 100);
                    $picture3 = new File(WWW_ROOT . "/img/uploads/images_resize/" . $oldProduct[0]['Product']['picture3']);
                    $picture3->delete();
                    $picture3 = new File(WWW_ROOT . "/img/uploads/" . $oldProduct[0]['Product']['picture3']);
                    $picture3->delete();
                } else {
                    if (!empty($requestimage3['tmp_name'])) {
                        $this->Product->invalidate('picture3', 'Please supply a valid image (.jpg, .gif or .png)');
                        $validate = false;
                    } else {
                        $this->request->data['Product']['picture3'] = NULL;
                    }
                }
                // Control Picture4 of Before
                $requestimage4 = $this->request->data['Product']['picture4'];
                $newfilename4 = date("YmdGis") . $requestimage4['name'];
                if (!empty($this->request->data['Product']['picture4']['name'])) {
                    $image4 = $newfilename4;
                } else {
                    $image4 = $oldProduct[0]['Product']['picture4'];
                }

                if (!empty($requestimage4['type']) && in_array($requestimage4['type'], $allowedMime)) {
                    if (!move_uploaded_file($requestimage4['tmp_name'], WWW_ROOT . 'img' . DS . 'uploads' . DS . $newfilename4)) {
                        $this->Product->invalidate('picture4', 'File was not uploaded, please try again.');
                        $validate = false;
                    } else {
                        $this->request->data['Product']['picture4'] = $newfilename4;
                    }

                    //indicate which file to resize (can be any type jpg/png/gif/etc...)
                    $file = 'img/uploads/' . $newfilename4;

                    //indicate the path and name for the new resized file
                    $resizedFile = 'img/uploads/images_resize/' . $newfilename4;
                    $this->smart_resize_image($file, 100, 100, false, $resizedFile, false, false, 100);
                    $picture4 = new File(WWW_ROOT . "/img/uploads/images_resize/" . $oldProduct[0]['Product']['picture4']);
                    $picture4->delete();
                    $picture4 = new File(WWW_ROOT . "/img/uploads/" . $oldProduct[0]['Product']['picture4']);
                    $picture4->delete();
                } else {
                    if (!empty($requestimage4['tmp_name'])) {
                        $this->Product->invalidate('picture4', 'Please supply a valid image (.jpg, .gif or .png)');
                        $validate = false;
                    } else {
                        $this->request->data['Product']['picture4'] = NULL;
                    }
                }
                $post_date = $this->request->data['Product']['posted_date']['year'] . '-' . $this->request->data['Product']['posted_date']['month'] . '-' . $this->request->data['Product']['posted_date']['day'] . ' ' . $this->request->data['Product']['posted_date']['hour'] . ':' . $this->request->data['Product']['posted_date']['min'];
                $expired_date = $this->request->data['Product']['expired_date']['year'] . '-' . $this->request->data['Product']['expired_date']['month'] . '-' . $this->request->data['Product']['expired_date']['day'] . ' ' . $this->request->data['Product']['expired_date']['hour'] . ':' . $this->request->data['Product']['expired_date']['min'];
                $modified_date = $this->request->data['Product']['modified_date']['year'] . '-' . $this->request->data['Product']['modified_date']['month'] . '-' . $this->request->data['Product']['modified_date']['day'] . ' ' . $this->request->data['Product']['modified_date']['hour'] . ':' . $this->request->data['Product']['modified_date']['min'];

                if ($this->Product->updateAll(
                                array(
                            'Product.category_id' => "'" . $this->request->data['Product']['category_id'] . "'",
                            'Product.user_id' => "'" . $this->request->data['Product']['user_id'] . "'",
                            'Product.title' => "'" . $this->request->data['Product']['title'] . "'",
                            'Product.status' => "'" . $this->request->data['Product']['status'] . "'",
                            'Product.type' => "'" . $this->request->data['Product']['type'] . "'",
                            'Product.price' => "'" . $this->request->data['Product']['price'] . "'",
                            'Product.description' => "'" . $this->request->data['Product']['description'] . "'",
                            'Product.location_id' => "'" . $this->request->data['Product']['location_id'] . "'",
                            'Product.address' => "'" . $this->request->data['Product']['address'] . "'",
                            'Product.picture1' => "'" . $image1 . "'",
                            'Product.picture2' => "'" . $image2 . "'",
                            'Product.picture3' => "'" . $image3 . "'",
                            'Product.picture4' => "'" . $image4 . "'",
                            'Product.posted_date' => "'" . $post_date . "'",
                            'Product.expired_date' => "'" . $expired_date . "'",
                            'Product.modified_date' => "'" . $modified_date . "'"
                                ), array('Product.id' => $id)
                        )) {
                    $this->Session->setFlash(__('The product has been saved.'));
                    return $this->redirect(array('action' => 'index'));
                } else {
                    $this->Session->setFlash(__('The product could not be saved. Please, try again.'));
                }
            } else {
                $options = array('conditions' => array('Product.' . $this->Product->primaryKey => $id));
                $this->request->data = $this->Product->find('first', $options);
            }
            Controller::loadModel('Category');
            $nodelist = $this->Category->generateTreeList(null, null, null, " - ");

//			$this->set('parents',$this->Category->generatetreelist());
            $this->set('parents', ($nodelist));
            $categories = $this->Product->Category->find('list');
            $users = $this->Product->User->find('list');
            $locations = $this->Product->Location->find('list');
            $this->set(compact('users', 'locations'));
            $this->set('products', $this->Product->find('first', array('conditions' => array('Product.id' => $id))));
        } else {
            return $this->redirect(array(
                        'controller' => 'pages',
                        'action' => 'index'));
        }
    }

    public function manageads() {
        $this->layout = 'home';
        Controller::loadModel('Product');
        Controller::loadModel('User');
        Controller::loadModel('Statistic');
        $userid=$this->Session->read('userid');
        if(!empty($userid)){
             $this->Paginator->settings = array(
            'limit' => 10,
            'conditions' => array('Product.user_id' => $userid)
        );
        }
        else {
        $this->Paginator->settings = array(
            'limit' => 10,
            'conditions' => array('Product.user_id' => $this->Auth->user('id'))
        );
        }
        $this->Product->recursive = 1;
        $this->set('products', $this->Paginator->paginate('Product'));

        $countstatistic = $this->Statistic->find('all', array('conditions' => array('Statistic.date' => $date = date('Y/m/d'))));
        $this->set('counttoday', $countstatistic);
    }

    public function adsadd() {
          parent::beforeFilter();
         $this->layout = 'home';
        Controller::loadModel('Categories');
        $this->set('cat_list', $this->Category->find('all', array('conditions' => array('Category.parent_id' => 0))));
    }

    public function login() {
        parent::beforeFilter();
         $this->layout = 'home';
        if ($this->Auth->user('role') && $this->Auth->user('role') == 'Register') {
            return $this->redirect(array(
                        'controller' => 'products',
                        'action' => 'add'));
        } else {
            Controller::loadModel('User');
            if ($this->request->is('post')) {
                $user = $this->request->data['User']['username'];
                $check = $this->User->find('first', array(
                    'conditions' => array('User.username' => $user)
                ));

                // check user activated
                if ($check && $check['User']['status'] != 0) {
                    if ($this->Auth->login()) {
                        if ($check['User']['role'] == 'Admin') {
                            return $this->redirect(array(
                                        'controller' => 'posts',
                                        'action' => 'adsadd'));
                        } else {
                            return $this->redirect(array(
                                        'controller' => 'posts',
                                        'action' => 'login'));
                        }
                    }
                    $this->Session->setFlash(__('Invalid username or password, try again'));
                } else {
                    $this->Session->setFlash(__('User not yet acivated'));
                }
            }
        }
    }

    public function register() {
         $this->layout = 'home';
        if ($this->Auth->user('role') && $this->Auth->user('role') == 'Register') {
            return $this->redirect(array(
                        'controller' => 'posts',
                        'action' => 'adsadd'));
        } else {
            Controller::loadModel('User');
            $encrypt = false;
            $key = 'encrypt';
            $iv = md5(md5($key));
            if ($this->request->is('post')) {
                $user_email = $this->request->data[User][email];

                $this->User->create();

                if ($this->User->save($this->request->data)) {
                    $this->Session->setFlash(__('you have successfully register with phsarkhmer. please check your email to activate your account'));
                    $id = $this->User->getLastInsertID();
                    $encrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $id, MCRYPT_MODE_CBC, $iv);
                    $encrypt = base64_encode($encrypt);

                    $idscript = str_replace(" ", "+", $encrypt);
                    // encrypt for send email to user to activate after register
                    //  echo $idscript;
                    //       echo '<a href="'.$this->webroot.'Users/resetemail/'.$idscript.'">reset</a>';

                    $user_message = 'Thank you for your register with phsarkhmer which is the best market ads listing in Cambodia.\r\n
                                    Please click linke below to activated your account during 24 hours:\r\n' . $this->webroot . 'posts/activated/' . $idscript;

                    $to = $user_email;
                    $subject = 'Activate Account -Phsarkhmer';
                    $message = $user_message;
                    $headers = 'From: no-reply@phsarkhmer.biz' . "\r\n" .
                            'Reply-To: no-reply@phsarkhmer.biz' . "\r\n";
                    mail($to, $subject, $message, $headers);



                    return $this->redirect(array(
                                'controller' => 'posts',
                                'action' => 'msregister'));
                } else {
                    $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
                }
            }
            $locations = $this->User->Location->find('list');
            $this->set(compact('locations'));
        }
    }

    public function msregister() {
        //    $this->Session->setFlash(__('you have been registered successfully, please go to check your email to activate your account'));
    }

    public function forgotpws() {
        $this->layout = 'home';
        Controller::loadModel('User');
        $encrypt = false;
        $key = 'encrypt';
        // initialization vector 
        $iv = md5(md5($key));
        if ($this->request->is('post')) {
            $email = $this->request->data['User']['email'];
            $check = $this->User->find('first', array(
                'conditions' => array('User.email' => $email)
            ));
            if (empty($check)) {
                $this->Session->setFlash(__('Email account is not exist!'));
                $this->redirect(array('controller' => 'posts', 'action' => 'forgotpws'));
            } else {
                $encrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $check['User']['id'], MCRYPT_MODE_CBC, $iv);
                $encrypt = base64_encode($encrypt);
                $this->Session->setFlash(__('email has been sent to your email address. please check it'));
                $idscript = str_replace(" ", "+", $encrypt);
                // echo $idscript;
                //   echo '<a href="'.$this->webroot.'posts/resetemail/'.$idscript.'">reset</a>';
                //change it to send an email when it live
                // $this->redirect(array('controller' => 'Users', 'action' => 'resetemail',$encrypt)); 
                $user_message = 'Thank you for your register with phsarkhmer which is the best market ads listing in Cambodia.\r\n
                                    Please click linke below to reset  your new password during 24 hours:\r\n' . $this->webroot . 'posts/resetemail/' . $idscript;

                $to = $user_email;
                $subject = 'Activate Account -Phsarkhmer';
                $message = $user_message;
                $headers = 'From: no-reply@phsarkhmer.biz' . "\r\n" .
                        'Reply-To: no-reply@phsarkhmer.biz' . "\r\n";
                mail($to, $subject, $message, $headers);

                return $this->redirect(array(
                            'controller' => 'posts',
                            'action' => 'msregister'));
            }
        }
    }
public function resent() {

	}
    public function activated($id = null) {
        Controller::loadModel('User');
        if ($this->request->is('post')){
         $token=$this->request->data['User']['token'];
         $code = $this->User->find('first', array(
                    'conditions' => array('User.token' => $token)
                 ));
         if($code){
            $this->User->updateAll(
                    array( 'User.status' => 1),   //fields to update
                    array( 'User.token' => $token)  //condition  
                );
             $this->Session->setFlash(__('Activated!'));
             return $this->redirect(array(
                        'controller' => 'posts',
                        'action' => 'login'));
         } else {
             $this->Session->setFlash(__('Activated Code is incorrect'));
             return $this->redirect(array(
                        'controller' => 'posts',
                        'action' => 'activated'));
         }
     }
    }

    public function resetemail($id = null) {
        Controller::loadModel('User');
        $idscript = str_replace(" ", "+", $id);
        //  echo $idscript;
        //   echo '<a href="'.$this->webroot.'Users/resetemail/'.$idscript.'">reset</a>';
        $descrypt = false;
        $key = 'encrypt';
        // initialization vector 
        $iv = md5(md5($key));
        $descrypt = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($idscript), MCRYPT_MODE_CBC, $iv);
        $descrypt = rtrim($descrypt, "");
        $ids = trim($descrypt);
        //  echo $ids;
        if ($this->request->is('post')) {
            $pass = $this->request->data['User']['password'];

            $password = AuthComponent::password($pass);
            $this->User->updateAll(
                    array('User.password' => "'" . $password . "'"), //fields to update
                    array('User.id' => $ids)  //condition  
            );
            return $this->redirect(array(
                        'controller' => 'posts',
                        'action' => 'login'));
        }
    }

    public function facelogout() {
        require '../../src/facebook.php';

        // Create our Application instance (replace this with your appId and secret).
        $facebook = new Facebook(array(
            'appId' => '624388847632649',
            'secret' => '832da640540ec5d0c33e2128111d8fb0',
            'cookie' => FALSE,
        ));
        $facebook->destroySession();
        $this->Session->delete('facebook');
        $this->Session->delete('userid');
         $this->Session->delete('bio');
         $this->Session->delete('gender');
         $this->Session->destroy();
        $facebook->getLogoutUrl();
        return $this->redirect(array(
                    'controller' => 'posts',
                    'action' => 'login'));
    }

    public function logout() {
        if ($this->Auth->logout()) {
            return $this->redirect(array(
                        'controller' => 'posts',
                        'action' => 'login'));
        }
    }


    public function index() {
          parent::beforeFilter();
         $this->layout = 'home';
        Controller::loadModel('Product');
        Controller::loadModel('Location');
        Controller::loadModel('Partner');
        Controller::loadModel('Comment');
        Controller::loadModel('Statistic');
        $productPromotion = $this->Product->Find('all', array('limit' => 10, 'conditions' => array('Product.type' => 'promotion')));
        $this->set('productPromotions', $productPromotion);
        // Latest product
        $product = $this->Product->Find('all', array('limit' => 10, 'order' => array('Product.posted_date' => 'desc')));
        $this->set('products', $product);

        // Feature product
        $products = $this->Product->Find('all', array('limit' => 10, 'order' => array('Product.modified_date' => 'desc')));
        $this->set('feartureproducts', $products);

        // Buy/Sale product
        $productsale = $this->Product->Find('all', array('limit' => 10, 'conditions' => array('Product.type' => 'sale')));
        $this->set('productsale', $productsale);

        // Partner
        $partners = $this->Partner->Find('all');
        $this->set('partners', $partners);

        // Popular product
        $popularProducts = $this->Product->Find('all', array('limit' => 10, 'order' => array('Product.view' => 'desc')));
        $this->set('popularProducts', $popularProducts);

        $countstatistic = $this->Statistic->find('all', array('conditions' => array('Statistic.date' => $date = date('Y/m/d'))));
        $this->set('counttoday', $countstatistic);

        $this->Post->recursive = 0;
        $this->set('posts', $this->Paginator->paginate());
        $this->set('params', '');
    }

    public function single($id = null) {
        $this->layout = 'default';
        if (!$this->Post->exists($id)) {
            throw new NotFoundException(__('Invalid blog'));
        }
        $options = array('conditions' => array('Post.' . $this->Post->primaryKey => $id));
        $this->set('post', $this->Post->find('first', $options));
    }

    public function admin() {
          $this->layout = 'default';  
        $this->Post->recursive = 0;
        $this->set('posts', $this->Paginator->paginate());
    }

    /**
     * view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function view($id = null) {
          parent::beforeFilter();
         $this->layout = 'home';
        Controller::loadModel('Product');
        Controller::loadModel('Statistic');
        Controller::loadModel('Comment');
        Controller::loadModel('User');

        // Add comments
        if ($this->request->is('post')) {
            $user_id = $this->request->data['Comment']['Email'];
            $this->Comment->create();
            $data = (
                    array(
                        'Comment' => array(
                            'comment' => $this->request->data['Comment']['Comments'],
                            'product_id' => $id
                        )
                    )
                    );
            if ($this->Comment->save($data)) {
                $email = $this->User->find('first', array(
                    'conditions' => array('User.id' => $user_id)
                ));
                $to = $email['User']['email'];
                $subject = 'Comments -Phsarkhmer';
                $message = $this->request->data['Comment']['Comments'];
                $headers = 'From: no-reply@phsarkhmer.biz' . "\r\n" .
                        'Reply-To: no-reply@phsarkhmer.biz' . "\r\n";
                mail($to, $subject, $message, $headers);
            }
        }

        // Count view of product
        $viewNum = $this->Product->find('first', array('fields' => array('Product.view'), 'conditions' => array('Product.id' => $id)));
        $this->Product->updateAll(
                array('Product.view' => $viewNum['Product']['view'] + 1), //fields to update
                array('Product.id' => $id)  //condition
        );

        // Start Count Statistic
        $findAll = $this->Statistic->find('all');
        $currentDate = date("Y-m-d");
        $boolean = 'true';
        foreach ($findAll as $each) {
            if ($each['Statistic']['product_id'] == $id AND $each['Statistic']['date'] == $currentDate) {
                $this->Statistic->updateAll(
                        array('Statistic.count' => $each['Statistic']['count'] + 1), //fields to update
                        array('AND' => array('Statistic.product_id' => $id, 'Statistic.date' => $currentDate))  //condition
                );
                $boolean = 'false';
            }
        }
        if ($id != 0) {
            if ($boolean == 'true') {
                $this->Statistic->create();
                $data = (
                        array(
                            'Statistic' => array(
                                'product_id' => $id,
                                'count' => 1,
                                'date' => $currentDate
                            )
                        )
                        );
                $this->Statistic->save($data);
            }
            $findAlls = $this->Statistic->find('all', array('conditions' => array('Statistic.product_id' => $id)));
            $this->set('statistics', $findAlls);
        }
        // End Count Statistic

        if (!$this->Product->exists($id)) {
            throw new NotFoundException(__('Invalid product'));
        }
        $options = array('conditions' => array('Product.' . $this->Product->primaryKey => $id));
        $this->set('product', $this->Product->find('first', $options));

        //$comments = $this->Comment->find('all');
        //$this->set('comments', $comments);
    }

    /**
     * add method
     *
     * @return void
     */
    public function allads() {
        parent::beforeFilter();
         $this->layout = 'home';
        Controller::loadModel('Product');
        $this->Paginator->settings = array(
            'limit' => 20
        );
        $this->Product->recursive = 0;
        $this->set('products', $this->Paginator->paginate('Product'));
    }

    public function article($id = null) {
        parent::beforeFilter();
         $this->layout = 'home';
        if (!$this->Post->exists($id)) {
            throw new NotFoundException(__('Invalid Post'));
        }
        $options = array('conditions' => array('Post.' . $this->Post->primaryKey => $id));
        $this->set('post', $this->Post->find('first', $options));
        $this->set('params', $id);
    }
     public function send(){
         $subject=$this->request->data['Posts']['Subject'];
         $fullname=$this->request->data['Posts']['Full Name'];
         $email=$this->request->data['Posts']['Email'];
         $phone=$this->request->data['Posts']['Phone'];
         $message=$this->request->data['Message'];
        $to      =  'lim.hou36@gmail.com';
        $subject = $subject."\r\n";
        $message = $subject."\r\n".$fullname."\r\n".$email."\r\n".$phone."\r\n".$message."\r\n";
        $headers = 'From: '.$email . "\r\n" . 
         'Reply-To: no-reply@phsarkhmer.biz' . "\r\n";
         mail($to, $subject, $message, $headers);
       
        echo '<p id="flashMessage"> You have been sent successfully!</p>';
     }
     public function contact($id = null) {
        
         $this->layout = 'home';
        if (!$this->Post->exists($id)) {
            throw new NotFoundException(__('Invalid Post'));
        }
        $options = array('conditions' => array('Post.' . $this->Post->primaryKey => $id));
        $this->set('post', $this->Post->find('first', $options));
        $this->set('params', $id);
        
    }

    public function add() {
      $this->layout = 'default';
        if ($this->Auth->user('role') && $this->Auth->user('role') == 'Admin') {
            if ($this->request->is('post')) {
                $this->Post->create();
                if ($this->Post->save($this->request->data)) {
                    $this->Session->setFlash(__('The page has been saved.'));
                    return $this->redirect(array('action' => 'admin'));
                } else {
                    $this->Session->setFlash(__('The page could not be saved. Please, try again.'));
                }
            }
        } else {
            return $this->redirect(array(
                        'controller' => 'posts',
                        'action' => 'admin'));
        }
        $this->set('params', '');
    }

    /**
     * edit method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function edit($id = null) {
        $this->layout = 'default';
        if ($this->Auth->user('role') && $this->Auth->user('role') == 'Admin') {
        Controller::loadModel('Product');
        if (!$this->Post->exists($id)) {
            throw new NotFoundException(__('Invalid page'));
        }
        if ($this->request->is(array('post', 'put'))) {
            if ($this->Post->save($this->request->data)) {
                $this->Session->setFlash(__('The page has been saved.'));
                return $this->redirect(array('action' => 'admin'));
            } else {
                $this->Session->setFlash(__('The page could not be saved. Please, try again.'));
            }
        } else {
            $options = array('conditions' => array('Post.' . $this->Post->primaryKey => $id));
            $this->request->data = $this->Post->find('first', $options);
        }
        }
    }

    /**
     * delete method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function delete($id = null) {
        Controller::loadModel('Product');
        Controller::loadModel('Comment');
        Controller::loadModel('Statistic');
        $this->Post->id = $id;
        $deletePro = $this->Product->find('all', array('conditions' => array('Product.id' => $id)));
        $this->Product->id = $id;
        if (!$this->Product->exists()) {
            throw new NotFoundException(__('Invalid product'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->Product->delete()) {
            $this->Session->setFlash(__('The product has been deleted.'));
            $picture1 = new File(WWW_ROOT . "/img/uploads/images_resize/" . $deletePro[0]['Product']['picture1']);
            $picture1->delete();
            $picture2 = new File(WWW_ROOT . "/img/uploads/images_resize/" . $deletePro[0]['Product']['picture2']);
            $picture2->delete();
            $picture3 = new File(WWW_ROOT . "/img/uploads/images_resize/" . $deletePro[0]['Product']['picture3']);
            $picture3->delete();
            $picture4 = new File(WWW_ROOT . "/img/uploads/images_resize/" . $deletePro[0]['Product']['picture4']);
            $picture4->delete();

            $picture1 = new File(WWW_ROOT . "/img/uploads/" . $deletePro[0]['Product']['picture1']);
            $picture1->delete();
            $picture2 = new File(WWW_ROOT . "/img/uploads/" . $deletePro[0]['Product']['picture2']);
            $picture2->delete();
            $picture3 = new File(WWW_ROOT . "/img/uploads/" . $deletePro[0]['Product']['picture3']);
            $picture3->delete();
            $picture4 = new File(WWW_ROOT . "/img/uploads/" . $deletePro[0]['Product']['picture4']);
            $picture4->delete();
        } else {
            $this->Session->setFlash(__('The product could not be deleted. Please, try again.'));
        }
        $this->deleteComment($id);
        $this->deletestatistic($id);
        
        return $this->redirect(array('controller' => 'posts', 'action' => 'manageads'));
    }

    public function search() {
          parent::beforeFilter();
         $this->layout = 'home';
        Controller::loadModel('Product');
        Controller::loadModel('Categories');
        Controller::loadModel('Statistic');

        $countstatistic = $this->Statistic->find('all', array('conditions' => array('Statistic.date' => $date = date('Y/m/d'))));
        $this->set('counttoday', $countstatistic);
        if ($this->request->is('post')) {
            $q = $this->request->data['Product']['q'];
            $category_id = $this->request->data['Product']['category_id'];
            $location_id = $this->request->data['Product']['location'];
            $sort = $this->request->data['Product']['filter'];
            //   $r=$this->Categories->query("select * from categories where parent_id=$category_id");

            $parent_id = $this->Categories->find('all', array('conditions' => array('Categories.parent_id' => $category_id)));
            $id = array();
            array_push($id, $category_id);
            foreach ($parent_id as $cat_id) {
                array_push($id, $cat_id['Categories']['id']);
            }


            //  $this->set('parent_id',$parent_id);

            $location = $this->request->data['Product']['location'];
            if ($q != "" && $category_id == "" && $location == "") {
                $options = array('conditions' =>
                    array('Product.title LIKE' => '%' . $q . '%'),
                    'order' => array('Product.title' => $sort)
                );
            } elseif ($q != "" && $category_id != "" && $location_id == "") {
                $options = array('conditions' => array('AND' =>
                        array('Product.title LIKE' => '%' . $q . '%'),
                        array('Product.category_id' => $id)),
                    'order' => array('Product.title' => $sort)
                );
            } elseif ($q == "" && $category_id != "" && $location_id != "") {
                $options = array('conditions' => array('AND' =>
                        array('Product.location_id' => $location_id),
                        array('Product.category_id' => $id)),
                    'order' => array('Product.title' => $sort)
                );
            } elseif ($q != "" && $category_id != "" && $location_id != "") {
                $options = array('conditions' => array('AND' =>
                        array('Product.title LIKE' => '%' . $q . '%'),
                        array('Product.category_id' => $id),
                        array('Product.location_id' => $location_id)),
                    'order' => array('Product.title' => $sort)
                );
            } elseif ($q != "" && $category_id == "" && $location_id != "") {
                $options = array('conditions' =>
                    array('AND' =>
                        array('Product.title LIKE' => '%' . $q . '%'),
                        array('Product.location_id' => $location_id)),
                    'order' => array('Product.title' => $sort));
            } elseif ($q == "" && $category_id != "" && $location == "") {

                $options = array('conditions' => array('Product.category_id' => $id), 'order' => array('Product.title' => $sort));
            } else {
                $options = array('conditions' => array('Product.location_id' => $location_id), 'order' => array('Product.title' => $sort));
            }

            if ($options) {
                $this->set('searches', $this->Product->find('all', $options));
            } else {
                $this->set('searches', $this->Product->find('all'));
            }
        } else {
            $this->set('searches', '');
        }
    }

    public function edituser($id = null) {
          parent::beforeFilter();
         $this->layout = 'home';
        //   echo $id;
        // die();
        $user=$this->Session->read('facebook');
        if($user=='facebook') {
           $this->set('profiles', 'facebook');
        }else {
        Controller::loadModel('User');
        Controller::loadModel('Location');
        if (!$this->User->exists($id)) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is(array('post', 'put'))) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('your profile has beend updated!.'));
                return $this->redirect(array('action' => 'edituser', $id));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        } else {
            $options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
            $this->request->data = $this->User->find('first', $options);
        }
        
        $locations = $this->User->Location->find('list');
        $this->set(compact('locations'));
         $this->set('profiles', '');
        }
    }
    
     /**
     * comment method
     *
     * @throws NotFoundException
     * 
     * 
     */
    public function comments() {
        $this->layout = 'home';
        Controller::loadModel('Product');
        Controller::loadModel('User');
        $userid=$this->Session->read('userid');
        if(!empty($userid)){
             $this->Paginator->settings = array(
            'limit' => 10,
            'conditions' => array('Product.user_id' => $userid)
        );
        }
        $this->Product->recursive = 1;
        $this->set('products', $this->Paginator->paginate('Product'));
    }
    
     /**
     * delete comment method
     *
     * @throws NotFoundException
     * 
     * 
     */

    public function deleteComment($id=null) {
            $statisticData = $this->Comment->find('all', array('conditions' => array('Comment.product_id' => $id)));
            foreach ($statisticData as $value) {
                $this->Comment->id = $value['Comment']['id'];
		if (!$this->Comment->exists()) {
			throw new NotFoundException(__('Invalid comment'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->Comment->delete()) {
			$this->Session->setFlash(__('The comment has been deleted.'));
		} else {
                    $this->Session->setFlash(__('The comment could not be deleted. Please, try again.'));
                }
            }
    }

public function deletepost($id) {
    if ($this->request->is('get')) {
        throw new MethodNotAllowedException();
    }

    if ($this->Post->delete($id)) {
        $this->Session->setFlash(
            __('The post with id: %s has been deleted.', h($id))
        );
        return $this->redirect(array('controller'=>'posts','action' => 'admin'));
    }
}
    
    /**
     * Delete statistic method
     *
     * @throws NotFoundException
     * 
     * 
     */
    public function deletestatistic($id) {
            $statisticData = $this->Statistic->find('all', array('conditions' => array('Statistic.product_id' => $id)));
            foreach ($statisticData as $value) {
                $this->Statistic->id = $value['Statistic']['id'];
                if (!$this->Statistic->exists()) {
                        throw new NotFoundException(__('Invalid statistic'));
                }
                $this->request->onlyAllow('post', 'delete');
                if ($this->Statistic->delete()) {
                        $this->Session->setFlash(__('The statistic has been deleted.'));
                } else {
                        $this->Session->setFlash(__('The statistic could not be deleted. Please, try again.'));
                }
            }
    }

    /**
     * resize image method
     *
     * @throws NotFoundException
     * 
     * 
     */
    public function smart_resize_image($file, $width = 0, $height = 0, $proportional = false, $output = 'file', $delete_original = true, $use_linux_commands = false, $quality = 100) {

        if ($height <= 0 && $width <= 0)
            return false;

        # Setting defaults and meta
        $info = getimagesize($file);
        $image = '';
        $final_width = 0;
        $final_height = 0;
        list($width_old, $height_old) = $info;
        $cropHeight = $cropWidth = 0;

        # Calculating proportionality
        if ($proportional) {
            if ($width == 0)
                $factor = $height / $height_old;
            elseif ($height == 0)
                $factor = $width / $width_old;
            else
                $factor = min($width / $width_old, $height / $height_old);

            $final_width = round($width_old * $factor);
            $final_height = round($height_old * $factor);
        }
        else {
            $final_width = ( $width <= 0 ) ? $width_old : $width;
            $final_height = ( $height <= 0 ) ? $height_old : $height;
            $widthX = $width_old / $width;
            $heightX = $height_old / $height;

            $x = min($widthX, $heightX);
            $cropWidth = ($width_old - $width * $x) / 2;
            $cropHeight = ($height_old - $height * $x) / 2;
        }

        # Loading image to memory according to type
        switch ($info[2]) {
            case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($file);
                break;
            case IMAGETYPE_GIF: $image = imagecreatefromgif($file);
                break;
            case IMAGETYPE_PNG: $image = imagecreatefrompng($file);
                break;
            default: return false;
        }


        # This is the resizing/resampling/transparency-preserving magic
        $image_resized = imagecreatetruecolor($final_width, $final_height);
        if (($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG)) {
            $transparency = imagecolortransparent($image);
            $palletsize = imagecolorstotal($image);

            if ($transparency >= 0 && $transparency < $palletsize) {
                $transparent_color = imagecolorsforindex($image, $transparency);
                $transparency = imagecolorallocate($image_resized, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
                imagefill($image_resized, 0, 0, $transparency);
                imagecolortransparent($image_resized, $transparency);
            } elseif ($info[2] == IMAGETYPE_PNG) {
                imagealphablending($image_resized, false);
                $color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
                imagefill($image_resized, 0, 0, $color);
                imagesavealpha($image_resized, true);
            }
        }
        imagecopyresampled($image_resized, $image, 0, 0, $cropWidth, $cropHeight, $final_width, $final_height, $width_old - 2 * $cropWidth, $height_old - 2 * $cropHeight);


        # Taking care of original, if needed
        if ($delete_original) {
            if ($use_linux_commands)
                exec('rm ' . $file);
            else
                @unlink($file);
        }

        # Preparing a method of providing result
        switch (strtolower($output)) {
            case 'browser':
                $mime = image_type_to_mime_type($info[2]);
                header("Content-type: $mime");
                $output = NULL;
                break;
            case 'file':
                $output = $file;
                break;
            case 'return':
                return $image_resized;
                break;
            default:
                break;
        }

        # Writing image according to type to the output destination and image quality
        switch ($info[2]) {
            case IMAGETYPE_GIF: imagegif($image_resized, $output);
                break;
            case IMAGETYPE_JPEG: imagejpeg($image_resized, $output, $quality);
                break;
            case IMAGETYPE_PNG:
                $quality = 9 - (int) ((0.9 * $quality) / 10.0);
                imagepng($image_resized, $output, $quality);
                break;
            default: return false;
        }

        return true;
    }

}
